
/**
 * 同步高德地图省市区数据
 */

var fs = require('fs')
const axios = require('axios')
const shell = require('shelljs')
const readline = require('readline')
const path = require('path')
const debug = require('debug')('sync-qqmap-area:*')

const AREA_LIST_URL = 'https://restapi.amap.com/v3/config/district'

const BASE_DIR = process.cwd()
// 输出目录
const OUTPUT_DIR = 'src/assets'

// 数据文件
const DATA_FILE = path.join(OUTPUT_DIR, 'area.js')
// 备份文件
const BACKUP_FILE = path.join(OUTPUT_DIR, 'area.bak.js')
const REAL_DATA_FILE = path.join(BASE_DIR, DATA_FILE)
const REAL_BACKUP_FIL = path.join(BASE_DIR, BACKUP_FILE)

let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

rl.question('是否同步高德地图省市区数据(y/n) ', input => {
  if (input === 'y' || input === 'yes') {
    main()
    rl.close()
    return
  }
  console.log('Bye!')
  rl.close()
  process.exit(1)
})

/**
 * 主入口
 */
function main () {
  debug('准备同步省市区数据')

  if (fs.existsSync(REAL_DATA_FILE)) {
    debug('开始备份')
    backup()
    debug('备份成功')
  } else {
    debug('没有数据可备份！')
  }

  debug('下载数据')

  // 官方api文档: https://lbs.amap.com/api/webservice/guide/api/district
  axios.get(AREA_LIST_URL, {
    params: {
      key: 'c8981983dad03bd778fc1b50cae70e54',
      subdistrict: 3
    }
  }).then(({ data }) => {
    if (data.status === '1') {
      let content = 'export default ' + JSON.stringify(transformData(data), null, 2)
      writeFileSync(content)
      debug('同步完成！')
    } else {
      throw new Error()
    }
  }).catch(error => {
    debug(error)
    debug('下载失败，正在恢复备份数据..')
    recover()
    debug('备份数据恢复完毕！')
  })
}

/**
 * 转换为与vant框架相同的数据结构
 */
function transformData (json) {
  var data = {
    province_list: {},
    city_list: {},
    county_list: {}
  }
  var provinces = json.districts[0].districts

  // 省
  provinces.forEach(province => {
    data.province_list[province.adcode] = province.name
    // 市
    province.districts.forEach(city => {
      data.city_list[city.adcode] = city.name
      // 区
      city.districts.forEach(county => {
        data.county_list[county.adcode] = county.name
      })
    })
  })

  return data
}
/**
 * 备份
 */
function backup () {
  shell.cp(REAL_DATA_FILE, REAL_BACKUP_FIL)
}
/**
 * 恢复
 */
function recover () {
  shell.mv(REAL_BACKUP_FIL, REAL_DATA_FILE)
}
/**
 * 创建文件并写入
 */
function writeFileSync (content) {
  fs.writeFileSync(REAL_DATA_FILE, content)
}
